package org.jmh.org.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.poi.ss.usermodel.Workbook;
import org.jmh.org.dto.UserDTO;
import org.jmh.org.service.IUserService;
import org.jmh.org.domain.User;
import org.jmh.org.query.UserQuery;
import org.jmh.base.util.AjaxResult;
import org.jmh.base.util.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    public IUserService userService;


    /**
     * 保存和修改公用的
     * @param user  传递的实体
     * @return Ajaxresult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody User user){
        try {
            if( user.getId()!=null)
                userService.update(user);
            else
                userService.insert(user);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("保存对象失败！"+e.getMessage());
        }
    }
    /**
    * 删除对象信息
    * @param id
    * @return
    */
    @DeleteMapping(value="/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            userService.delete(id);
            return AjaxResult.success();
        } catch (Exception e) {
        e.printStackTrace();
            return AjaxResult.error("删除对象失败！"+e.getMessage());
        }
    }

    //获取用户
    @GetMapping("/{id}")
    public AjaxResult get(@PathVariable("id")Long id)
    {
        try {
            User user = userService.selectById(id);
            return AjaxResult.success(user);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取一个失败！"+e.getMessage());
        }
    }


    /**
    * 查看所有的用户信息
    * @return
    */
    @GetMapping
    public AjaxResult list(){

        try {
            List< User> list = userService.selectAll();
            return AjaxResult.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取所有失败！"+e.getMessage());
        }
    }


    /**
    * 分页查询数据
    *
    * @param query 查询对象
    * @return PageList 分页对象
    */
    @PostMapping
    public AjaxResult json(@RequestBody UserQuery query)
    {
        try {
            PageInfo<User> pageInfo = userService.queryPage(query);
            return AjaxResult.success(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("获取分页数据失败！"+e.getMessage());
        }
    }



    /**
    * 批量删除
    * @return
    */
    @PatchMapping
    public AjaxResult batchDelete(@RequestBody List<Long> ids){

        try {
            userService.batchDelete(ids);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("批量删除所有失败！"+e.getMessage());
        }
    }


    @ResponseBody
    @PostMapping ("/importData")
    public AjaxResult upload(@RequestParam("file") MultipartFile multipartFile) throws Exception {
        //new一个模板
        ImportParams params = new ImportParams();
        //设置表格标题行数,默认0，这是读取时会跳过的行数
        params.setTitleRows(1);
        //表头行数,默认1。上午提到，如果有合并的列名，就要设置读取表头的行数
        params.setHeadRows(2);
        //开始读取，并用list接收，方便处理
        List<User> result = ExcelImportUtil.importExcel(multipartFile.getInputStream(), User.class, params);
        System.out.println(new ObjectMapper().writeValueAsString(result));
        try {
            userService.imports(result);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("导入失败！"+e.getMessage());
        }
    }

    @RequestMapping("/down")
    public AjaxResult export1(@RequestBody UserDTO dto, String title) {
        List<User> result = dto.getResult();
        for(User users:result){
            System.out.println(users);
        }
//  输出到本地地址
        try {
            ExportParams params = new ExportParams(title, "sheet1", ExcelType.XSSF);
            Workbook workbook = ExcelExportUtil.exportExcel(params,User.class, dto.getResult());
            File saveFile = new File("excel");
            if (!saveFile.exists()) {
                saveFile.mkdirs();
            }
            //地址
            FileOutputStream fos = new FileOutputStream("D:/360MoveData/Users/79196/Desktop/2.xlsx");
            workbook.write(fos);
            fos.close();
            return AjaxResult.success(fos);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("导入失败！"+e.getMessage());
        }
    }


}
